﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;

namespace xmlTranslate
{
    public class BaiduAPI : ITranslate
    {
        readonly string urlBase = "";
        const string APPID = "";
        const string key = "";
        const string salt = "";
        public BaiduAPI()
        {
            urlBase = $"https://fanyi-api.baidu.com/api/trans/vip/translate?from=auto&to=auto&appid={APPID}&salt={salt}";
        }
        public string Translate(string sourceStr, bool saveSource = true)
        {
            HttpHelper httpHelper = new HttpHelper();
            var request = httpHelper.GetHtml(new HttpItem
            {
                URL = urlBase + $"&q={sourceStr}&sign={GetSign(sourceStr)}"
            });

            try
            {
                var result = JsonConvert.DeserializeObject<BaiDuApiResult>(request.Html);
                if (result.error_code == 52000 || result.error_code == 0)
                {
                    string str = result.trans_result.FirstOrDefault()?.dst;
                    if (str != null)
                    {
                        if (saveSource)
                            return $"{str}({sourceStr})";
                    }
                }
                if (result.error_code == 54003)
                {
                    Thread.Sleep(1000);
                    return Translate(sourceStr, saveSource);
                }
                return sourceStr;
            }
            catch
            {
                return sourceStr;
            }
        }

        public string GetSign(string q)
        {
            return md5($"{APPID}{q}{salt}{key}");
        }


        /// <summary>
        /// 获取大写的MD5签名结果
        /// </summary>
        /// <param name="encypStr"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        public static string GetMD5(string encypStr, string charset)
        {
            string retStr;
            MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();

            //创建md5对象
            byte[] inputBye;
            byte[] outputBye;

            //使用GB2312编码方式把字符串转化为字节数组．
            try
            {
                inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr);
            }
            catch (Exception ex)
            {
                inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);
            }
            outputBye = m5.ComputeHash(inputBye);
            m5.Clear();
            retStr = System.BitConverter.ToString(outputBye);
            retStr = retStr.Replace("-", "").ToLower();
            return retStr;
        }

        public static string md5(string str)
        {
            try
            {
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                byte[] bytValue, bytHash;
                bytValue = System.Text.Encoding.UTF8.GetBytes(str);
                bytHash = md5.ComputeHash(bytValue);
                md5.Clear();
                string sTemp = "";
                for (int i = 0; i < bytHash.Length; i++)
                {
                    sTemp += bytHash[i].ToString("X").PadLeft(2, '0');
                }
                str = sTemp.ToLower();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return str;
        }

    }


    public class BaiDuApiResult
    {
        public string from { get; set; }
        public string to { get; set; }
        public List<BaiDuApiTransResult> trans_result { get; set; }
        public int error_code { get; set; }
    }
    public class BaiDuApiTransResult
    {
        public string src { get; set; }
        public string dst { get; set; }
    }
}
